<?php

namespace app\lnk\controller;

use app\lnk\model\CommentModel;
use app\lnk\model\DynamicModel;
use app\lnk\model\DynamicImgModel;
use app\lnk\model\DynamicVideoModel;
use app\lnk\model\MessageModel;
use app\lnk\model\UserLikeDynamicModel;
use lite\controller\Backend;
use lite\controller\traits\Crud;
use think\facade\Db;
use lite\lib\help;
use think\Request;

class Videonews extends Backend
{
    use Crud;

    public function initialize()
    {
        $this->model = new DynamicModel();
    }

    public function index(Request $request)
    {
        $params = $request->get();

        if (!empty($request->param('page_size'))) {       // 使用分页
            $query = $this->model->with('user')->append(['like_count', 'comment_count'])
                ->withAttr('like_count', function ($value, $data) {
                    return UserLikeDynamicModel::where('dynamic_id', $data['id'])->count();
                })->withAttr('comment_count', function ($value, $data) {
                    return CommentModel::where('status', '<>', 0)->where('dynamic_id', $data['id'])->count();
                });
            if ($params['content']) $query = $query->where('content', 'like', '%' . $params['content'] . '%');
            if ($params['id']) $query = $query->where('id', $params['id']);
            if ($params['type'] >= 0) $query = $query->where('type', $params['type']);
            if ($params['status'] >= 0) $query = $query->where('status', $params['status']);
            $query = $query->where('mod', 1);
            $list = $query->order(['status' => 'asc', 'top' => 'desc', 'create_time' => 'desc', 'view' => 'desc'])->paginate($request->param('page_size', 10));
        } else {
            $list = $this->model->order('status', 'asc')->order('weigh', 'desc')->order('id', 'desc')->select();               // 查询全部
        }

        return success('获取成功', $list);
    }


    public function save(Request $request)
    {
        $params = $request->param();
        
        if (empty($params['img']) || empty($params['url'])) {
            return error('封面图或视频地址为空');
        }

        $uid = 100002;
        $time = time();
        $model = ['user_id' => $uid, 'content' => $params['content'], 'type' => 2,'circle_id' => 0];
        $model += ['status' => 1];
        $model += ['mod' => 1];
        $model += ['create_time' => $time];
        $ip = $request->ip();
        $model += ['ip' => $ip];
        $res = help::ip($ip);
        if ($res['status'] == 0) {

            $model += ['country' => $res['result']['ad_info']['nation']];
            $model += ['province' => $res['result']['ad_info']['province']];
            $model += ['city' => $res['result']['ad_info']['city']];
            $model += ['district' => $res['result']['ad_info']['district']];
        }
        $id = (new DynamicModel)->insertGetId($model);

        DynamicVideoModel::insert([
            'url' => $params['url'],
            'img' => $params['img'],
            'wide' => 1920,
            'high' => 1080,
            'dynamic_id' => $id,
            'user_id' => $uid,
            'update_time' => $time
        ]);

        return success('保存成功',$this->model);
    }

    public function read($id)
    {
        $detail = $this->model->findOrFail($id);
        if ($detail->type == 1) $detail->imgs = DynamicImgModel::where('dynamic_id', $id)
            ->order('weigh', 'asc')
            ->field('url,wide,high')
            ->select();
        if ($detail->type == 2) $detail->video = DynamicVideoModel::where('dynamic_id', $id)
            ->field('img,url,wide,high')
            ->find();
        return success('获取成功', $detail);
    }

    public function update(Request $request)
    {
        $params = $request->all();
        // 发送驳回消息通知用户
        if ($params['status'] == 3 && $params['reason']) {
            $content = "驳回原因：" . $params['reason'] . "；您可以编辑后重发布";
            if ($params['type'] == 1) {
                $img = DynamicImgModel::where('dynamic_id', $params['id'])->order('weigh', 'asc')->value('url');
            } else if ($params['type'] == 2) {
                $img = DynamicVideoModel::where('dynamic_id', $params['id'])->value('img');
            }
            $content_url = '/pages/dynamic/details?id=' . $params['id'];
            (new MessageModel())->send($params['user_id'], '动态被驳回', $content, 1, $img ?? '', '', $content_url);
        }
        $this->model->where('id', $params['id'])->update([
            'top' => $params['top'],
            'show' => $params['show'],
            'weigh' => $params['weigh'],
            'status' => $params['status'],
        ]);
        return success('保存成功');
    }

    public function delete($id)
    {
        $pk = $this->model->getPk();

        $result = Db::transaction(function () use ($id, $pk) {
            $count = 0;
            foreach ($this->model->whereIn($pk, $id)->cursor() as $row) {
                $count += $row->delete();
                // 删除用户关注的动态
                UserLikeDynamicModel::where('dynamic_id', $id)->delete();
            }
            return $count;
        });
        if ($result) {
            return success('删除成功', $result);
        }
        return error('删除失败');
    }

}
